class StoreController < ApplicationController

  before_filter :find_cart, :find_user  # this means that before any of the public actions (here, index, add_to_cart, etc), the method find_cart will be called.

  def index
    @articles = Article.find_articles_for_sale	
    @message = "Viewing All Articles"
    @category = Category.find_by_name("All")
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @articles }
    end
  end

  def add_to_cart
    article = Article.find(params[:id])
    @current_item = @cart.add_article(article)  # we make an instance variable so we always know what is the most recent item we have done something with.
    flash[:notice] = "Item added sucessfully to your shopping cart"
    respond_to do |format|
      format.js if request.xhr? #if the browser's request was a .js request (not an HTTP request), look for add_to_cart.js.rjs and do that.
      format.html { # index.html.erb
        redirect_to(:action => "index") 
      }
    end

  end
  def remove_from_cart
    article =  Article.find(params[:id])
    @cart.remove_article(article)
    @current_item = nil
    flash[:notice] = "Item sucessfully removed from your shopping cart"
    respond_to do |format|
      format.js if request.xhr? # this if request.xhr? is how you determine if a browser has .js enabled.
      format.html { # index.html.erb
        redirect_to(:action => "index") 
      }
    end
  end
  
  def empty_cart 
    session[:cart] = nil 
    flash[:notice] = "Your cart is currently empty" 
    redirect_to :action => 'index'
  end
  
  def checkout
    if @cart.cart_items.empty?
      redirect_to_index("Your cart is empty!")
    elsif @user.nil?
      authorize_customer #calls a method to make sure one logs in.
    else
      @order = Order.new # this can be seen like a temp object that the form requires
    end  
    # this is where it renders the checkout.html.erb action
    
  end
  
  def save_order
    #params[:order] mean what gets submitted in the form in checkout.html.  Because there we use the 
    # form_for ... tag, with :order as an argument.  So when you hit submit, those go in the params hash.
    
      authorize_customer
      @order = Order.new(params[:order])
      @order.add_order_items_from_cart(@cart)
	  
       
      # if I actually wanted to use the user's stuff
      if params[:override_address] == "no"
        @order.street = @user.address.street
        @order.streetNr = @user.address.streetNr
        @order.city = @user.address.city
        @order.zip = @user.address.zip
      end
	  
   
      if @order.save #if it saves correctly it returns true
		 
		 #order_items has to be saved in DB
		 @cart.cart_items.each do |c|
		   @oi = OrderItem.new(:article_id => c.article.id, :order_id => @order.id, :quantity => c.quantity, :total_price => c.price)
	       @oi.save
		  end

		 if(@order.email != @user.email)
		    Order.find(:all, :conditions => ['email = ?', @user.email]).each do |o| 
			  o.update_attributes({ :email => @order.email })
			end
			User.find(:all, :conditions => ['email = ?', @user.email]).each do |u|
			  u.update_attributes({ :email => @order.email })
			end
		 end
		 
		
		session[:cart] = nil  # empties / removes the cart
        redirect_to_index("Thank you for your order") # this redirects to the index action and puts that string in the flash[:notice] variable.  
      else
        flash[:notice] = "Could not place your order.  Perhaps trying again will help."
        render :action => 'checkout'
      end

  end

  def delete_from_cart
	 article =  Article.find(params[:id])
    @cart.delete_article(article)
    @current_item = nil
	  flash[:notice] = "Article sucessfully removed from your shopping cart"
	  respond_to do |format|
		  format.js if request.xhr?
		  format.html { # index.html.erb
		    redirect_to(:action => "index") 
		  }
	  end
  end
  
  def search
    logger.debug "SEARCHING..."
    @articles = Article.search(params[:query])
    @message = "Viewing Search Results"
    
    # it renders the store/index.html.erb template but uses the variables here.
    respond_to do |format|
      format.html { render :action => "index"}
      format.xml  { render :xml => @articles }
    end
  end
  
  def filter
    logger.debug "FILTERING..."
    @category = Category.find(params[:category])
    @articles = @category.articles
    @message = "Viewing "+@category.name
    
    # it renders the store/index.html.erb template but uses the variables here.
    respond_to do |format|
      format.html { render :action => "index"}
      format.xml  { render :xml => @articles }
    end
  end
    
  
  def detail
    @article = Article.find(params[:id])	
    @message = "Viewing Article Details"
    @category = Category.find(@article.category_id)
	    
	respond_to do |format|
	  format.html { render :action => "index"}
      format.xml  { render :xml => @article }
    end

  end
  
  def user_profile
    @user = User.find(params[:id])	
    @message = "Viewing User Profile"
	    
	respond_to do |format|
	  format.html { render :action => "index"}
      format.xml  { render :xml => @user }
    end

  end  
  
  def view_orders
    @user = User.find(params[:id])	
    @message = "Viewing All Orders"
	  @orders = Order.find(:all, :conditions => ['email = ?', @user.email]);
	    
	respond_to do |format|
	  format.html { render :action => "index"}
      format.xml  { render :xml => @user }
    end

  end 
	
	
  protected
  def authorize
    # WHITELIST.  Anyone can call actions from the store controller.
  end
  
  def authorize_customer
    user = User.find_by_id(session[:user_id]) 
    unless user
      session[:original_uri] = request.request_uri # keep the address of where they were
      flash[:notice] = "Please log in to continue" 
      redirect_to :controller => 'admin', :action => 'login'
    end
  end
  
  private
  
  def redirect_to_index(msg)
    flash[:notice] = msg
    redirect_to :action => 'index'
  end

  def find_cart
    unless session[:cart]
      session[:cart] = Cart.new
    end
    @cart = session[:cart]
  end
  

end
